package com.approval.approvalapp.index;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approval.LocationService;
import com.approval.approvalapp.MyAppliaction;
import com.approval.approvalapp.R;
import com.approval.approvalapp.bean.DkListBean;
import com.approval.approvalapp.myself.activity.WdkqActivity;
import com.approval.approvalapp.util.ErrorBeanUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.google.gson.JsonObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class QdActivity extends BaseActivity {


    @Bind(R.id.back_iv)
    ImageView backIv;
    @Bind(R.id.titleTv1)
    TextView titleTv1;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.wdkq_ll)
    LinearLayout wdkqLl;
    @Bind(R.id.gh)
    TextView gh;
    @Bind(R.id.sxbdk_tv)
    TextView sxbdkTv;
    @Bind(R.id.time_tv)
    TextView timeTv;
    @Bind(R.id.civ_ll)
    LinearLayout civLl;
    @Bind(R.id.ico_iv)
    ImageView icoIv;
    @Bind(R.id.fw_tv)
    TextView fwTv;
    @Bind(R.id.cxdw)
    TextView cxdw;
    @Bind(R.id.rv1)
    RecyclerView rv1;

    private boolean isfanwei;
    private String latitudestr;
    private String longitudestr;
    LocationManager locationManager;


    private LocationService locationService;

    @Override
    public int getLayoutId() {
        return R.layout.activity_qd;
    }

    @Override
    public void initView() {
        backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                leave = true;
                finish();
            }
        });
        wdkqLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QdActivity.this, WdkqActivity.class);
                startActivity(intent);
            }
        });


        cxdw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationManager = (LocationManager) QdActivity.this.getSystemService(Context.LOCATION_SERVICE);
                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//                    getLocation();
                    //gps已打开
                    locationService.start();// 定位SDK
                } else {
                    Intent i = new Intent();
                    i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(i, 100);
                }

            }
        });

        civLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isfanwei) {
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("gh", SpUtil.getString(QdActivity.this, SpUtil.GH, ""));
                jsonObject.put("longitude", longitudestr);
                jsonObject.put("latitude", latitudestr);
                NetRequsetUtil.getInstance().netRequestPostJson("v1/user/insert_clock_in", jsonObject.toString(), new NetDownResponse() {
                    @Override
                    public void success(String str) {
                        Toast.makeText(QdActivity.this, "签到成功", Toast.LENGTH_SHORT).show();
                        // TODO: 2019/5/23 刷新列表
                        refreshRv();
                    }

                    @Override
                    public void errowithresponse(String str) {
                        ErrorBeanUtil.getErrorMessage(str);


                    }

                    @Override
                    public void erro() {

                    }

                    @Override
                    public void finish() {


                    }
                });
            }
        });


        MThread mThread = new MThread();
        mThread.start();
        name.setText(SpUtil.getString(this, SpUtil.USER_RUN_NICKNAME, ""));
        gh.setText("工号: " + SpUtil.getString(this, SpUtil.GH, ""));

        latitudestr = getIntent().getStringExtra("latitudestr");
        longitudestr = getIntent().getStringExtra("longitudestr");


        refreshRv();

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("获取经纬度");
        progressDialog.show();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gh", SpUtil.getString(this, SpUtil.GH, ""));
        jsonObject.put("longitude", longitudestr);
        jsonObject.put("latitude", latitudestr);
        Log.d("QdActivity33", jsonObject.toString());
        NetRequsetUtil.getInstance().netRequestPostJson("v1/user/clock_in", jsonObject.toString(), new NetDownResponse() {
            @Override
            public void success(String str) {
                Log.d("QdActivity33", str);

                isfanwei = true;
                civLl.setBackgroundResource(R.drawable.btn_punch_on);
                sxbdkTv.setTextColor(Color.parseColor("#ffffff"));
                timeTv.setTextColor(Color.parseColor("#FFFDE5C3"));
                fwTv.setText("已进入考勤范围");
                icoIv.setBackgroundResource(R.drawable.location_pass);


            }

            @Override
            public void errowithresponse(String str) {
                Toast.makeText(QdActivity.this, "不在范围", Toast.LENGTH_SHORT).show();
                isfanwei = false;
                civLl.setBackgroundResource(R.drawable.btn_punch_off);
                sxbdkTv.setTextColor(Color.parseColor("#FFE0E1E6"));
                timeTv.setTextColor(Color.parseColor("#FFD0D1D9"));
                fwTv.setText("不在考勤范围");
                icoIv.setBackgroundResource(R.drawable.location_mistake);


            }

            @Override
            public void erro() {

            }

            @Override
            public void finish() {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }

            }
        });


        //两个列表
//        NetRequsetUtil.getInstance().netRequestPostJson("");

    }

    @Override
    public void initData() {

    }

    class MThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                if (leave) {
                    return;
                }
                long l = System.currentTimeMillis();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                Date date = new Date(l);
                final String format = simpleDateFormat.format(date);

                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");

                final String format1 = simpleDateFormat1.format(date);


                final boolean inTime1 = isInTime("00:01-17:00", format1);
                Log.d("MThread", "simpleDateFormat1:" + format1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        timeTv.setText(format);

                        if (inTime1) {
                            sxbdkTv.setText("上班打卡");
                        } else {
                            sxbdkTv.setText("下班打卡");
                        }
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    boolean leave;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        leave = true;
    }


    public static boolean isInTime(String sourceTime, String curTime) {
        if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
            throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
        }
        if (curTime == null || !curTime.contains(":")) {
            throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
        }
        String[] args = sourceTime.split("-");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        try {
            long now = sdf.parse(curTime).getTime();
            long start = sdf.parse(args[0]).getTime();
            long end = sdf.parse(args[1]).getTime();
            if (args[1].equals("00:00")) {
                args[1] = "24:00";
            }
            if (end < start) {
                if (now >= end && now < start) {
                    return false;
                } else {
                    return true;
                }
            } else {
                if (now >= start && now < end) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
        }

    }

    private void getLocation() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String lstr = latitude + "";
            String longtr = longitude + "";
            String latitudestr = lstr.substring(0, 5);
            String longitudestr = longtr.substring(0, 6);

            // TODO: 2019/5/23
            QdActivity.this.latitudestr = latitudestr;
            QdActivity.this.longitudestr = longitudestr;


            final ProgressDialog progressDialog = new ProgressDialog(QdActivity.this);
            progressDialog.setMessage("获取经纬度");
            progressDialog.show();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("gh", SpUtil.getString(QdActivity.this, SpUtil.GH, ""));
            jsonObject.put("longitude", longitudestr);
            jsonObject.put("latitude", latitudestr);
            NetRequsetUtil.getInstance().netRequestPostJson("v1/user/clock_in", jsonObject.toString(), new NetDownResponse() {
                @Override
                public void success(String str) {
                    isfanwei = true;
                    civLl.setBackgroundResource(R.drawable.btn_punch_on);
                    sxbdkTv.setTextColor(Color.parseColor("#ffffff"));
                    timeTv.setTextColor(Color.parseColor("#FFFDE5C3"));
                    fwTv.setText("已进入考勤范围");
                    icoIv.setBackgroundResource(R.drawable.location_pass);


                }

                @Override
                public void errowithresponse(String str) {
                    Toast.makeText(QdActivity.this, "不在范围", Toast.LENGTH_SHORT).show();
                    isfanwei = false;
                    civLl.setBackgroundResource(R.drawable.btn_punch_off);
                    sxbdkTv.setTextColor(Color.parseColor("#FFE0E1E6"));
                    timeTv.setTextColor(Color.parseColor("#FFD0D1D9"));
                    fwTv.setText("不在考勤范围");
                    icoIv.setBackgroundResource(R.drawable.location_mistake);


                }

                @Override
                public void erro() {

                }

                @Override
                public void finish() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }

                }
            });


        } else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        }

    }

    LocationListener locationListener = new LocationListener() {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("MainActivity", "1");
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
            Log.d("MainActivity", "1");
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("MainActivity", "1");

        }

        // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                Log.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String lstr = latitude + "";
                String longtr = longitude + "";
                String latitudestr = lstr.substring(0, 5);
                String longitudestr = longtr.substring(0, 6);

                QdActivity.this.latitudestr = latitudestr;
                QdActivity.this.longitudestr = longitudestr;

                // TODO: 2019/5/23
                final ProgressDialog progressDialog = new ProgressDialog(QdActivity.this);
                progressDialog.setMessage("获取经纬度");
                progressDialog.show();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("gh", SpUtil.getString(QdActivity.this, SpUtil.GH, ""));
                jsonObject.put("longitude", longitudestr);
                jsonObject.put("latitude", latitudestr);
                NetRequsetUtil.getInstance().netRequestPostJson("v1/user/clock_in", jsonObject.toString(), new NetDownResponse() {
                    @Override
                    public void success(String str) {
                        isfanwei = true;
                        civLl.setBackgroundResource(R.drawable.btn_punch_on);
                        sxbdkTv.setTextColor(Color.parseColor("#ffffff"));
                        timeTv.setTextColor(Color.parseColor("#FFFDE5C3"));
                        fwTv.setText("已进入考勤范围");
                        icoIv.setBackgroundResource(R.drawable.location_pass);


                    }

                    @Override
                    public void errowithresponse(String str) {
                        Toast.makeText(QdActivity.this, "不在范围", Toast.LENGTH_SHORT).show();
                        isfanwei = false;
                        civLl.setBackgroundResource(R.drawable.btn_punch_off);
                        sxbdkTv.setTextColor(Color.parseColor("#FFE0E1E6"));
                        timeTv.setTextColor(Color.parseColor("#FFD0D1D9"));
                        fwTv.setText("不在考勤范围");
                        icoIv.setBackgroundResource(R.drawable.location_mistake);


                    }

                    @Override
                    public void erro() {

                    }

                    @Override
                    public void finish() {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }

                    }
                });

            } else {
                Log.d("MainActivity", "gg");
            }
        }
    };

    public void refreshRv(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gh" , SpUtil.getString(this , SpUtil.GH , ""));
        NetRequsetUtil.getInstance().netRequestPostJson("v1/user/get_qd_record", jsonObject.toString(), new NetDownResponse() {
            @Override
            public void success(String str) {
                DkListBean dkListBean = JSON.parseObject(str, DkListBean.class);
                List<DkListBean.MorningBean> morning = dkListBean.getMorning();

                rv1.setLayoutManager(new LinearLayoutManager(QdActivity.this));

                RvAdapter rvAdapter1 = new RvAdapter();
                rvAdapter1.setList(morning);
                rv1.setAdapter(rvAdapter1);

            }

            @Override
            public void errowithresponse(String str) {

            }

            @Override
            public void erro() {

            }

            @Override
            public void finish() {

            }
        });
    }


    class RvAdapter extends RecyclerView.Adapter<RvAdapter.Holder>{

        List<DkListBean.MorningBean> list;

        public void setList(List<DkListBean.MorningBean> list) {
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tew,parent,false);
            Holder holder = new Holder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(Holder holder, int position) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM-dd HH:mm");
            Long timeStamp = new Long(list.get(position).getQd_time()) * 1000;  //获取当前时间戳
            String timese = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
            holder.tv.setText(timese);
        }

        @Override
        public int getItemCount() {
            if (list == null){
                return 0;
            }else {
            return list.size();
            }
        }

        class Holder extends RecyclerView.ViewHolder{
            TextView tv;
            public Holder(View itemView) {
                super(itemView);
                tv = itemView.findViewById(R.id.tv);
            }
        }
    }


    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //经度
                double longitude = location.getLongitude();
                //纬度
                double latitude = location.getLatitude();

                locationService.stop();

                String lstr = latitude + "";
                String longtr = longitude + "";
                String latitudestr = lstr.substring(0, 5);
                String longitudestr = longtr.substring(0, 6);

                QdActivity.this.latitudestr = latitudestr;
                QdActivity.this.longitudestr = longitudestr;

                Log.d("QdActivity33", location.getLocTypeDescription());

                // TODO: 2019/5/23
                final ProgressDialog progressDialog = new ProgressDialog(QdActivity.this);
                progressDialog.setMessage("获取经纬度");
                progressDialog.show();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("gh", SpUtil.getString(QdActivity.this, SpUtil.GH, ""));
                jsonObject.put("longitude", longitudestr);
                jsonObject.put("latitude", latitudestr);
                Log.d("QdActivity33", jsonObject.toString());
                NetRequsetUtil.getInstance().netRequestPostJson("v1/user/clock_in", jsonObject.toString(), new NetDownResponse() {
                    @Override
                    public void success(String str) {
                        isfanwei = true;
                        civLl.setBackgroundResource(R.drawable.btn_punch_on);
                        sxbdkTv.setTextColor(Color.parseColor("#ffffff"));
                        timeTv.setTextColor(Color.parseColor("#FFFDE5C3"));
                        fwTv.setText("已进入考勤范围");
                        icoIv.setBackgroundResource(R.drawable.location_pass);


                    }

                    @Override
                    public void errowithresponse(String str) {
                        Toast.makeText(QdActivity.this, "不在范围", Toast.LENGTH_SHORT).show();
                        isfanwei = false;
                        civLl.setBackgroundResource(R.drawable.btn_punch_off);
                        sxbdkTv.setTextColor(Color.parseColor("#FFE0E1E6"));
                        timeTv.setTextColor(Color.parseColor("#FFD0D1D9"));
                        fwTv.setText("不在考勤范围");
                        icoIv.setBackgroundResource(R.drawable.location_mistake);


                    }

                    @Override
                    public void erro() {

                    }

                    @Override
                    public void finish() {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }

                    }
                });

            }
        }

    };

    @Override
    public void onResume() {
        super.onResume();
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService = ((MyAppliaction) this.getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());

    }

    @Override
    public void onStop() {
        super.onStop();
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

}
